﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;

namespace MBBHotelReservation
{
    public partial class frmPackageDetails : Form
    {
        UnityProcessor proc = new UnityProcessor();
        UnityScript[] dat = new UnityScript[0];
        Threader t = new Threader();

        DataTable room = new DataTable();
        DataTable functionhall = new DataTable();
        DataTable amenities = new DataTable();
        DataTable food = new DataTable();

       // string[] lstamenities = {"POOL", "RESTAURANT", "GYM", "SPA" };
        string[] lstreservation = { "ROOM", "FUNCTION HALL"};
        string[] lstmealtime = { "BREAKFAST", "SNACK AM", "LUNCH", "SNACK PM", "DINNER" };


        List<string> lstADetails = new List<string>();
        List<string> lstRDetails = new List<string>();
        List<string> lstFDetails = new List<string>();
        List<string> lstFoodDetails = new List<string>();
        List<string> lstamenities = new List<string>();


        string packageName = "", packageID = "", wrnEntMsg= "";
        bool prcErr = false, pamtErr = false, amtErr = false;
        int typesel = -1;
        int curDat = -1;

        public struct PackageItemDetailType
        {
            public bool isNew;
            public string dbKey;
            public string KeyID;
            public string StringData;
            public DateTime DateTimeData;
            public float NumericData;
        }

        public frmPackageDetails(string package, string id)
        {
            packageName = package;
            packageID = id;
            InitializeComponent();
            proc.ProcessError += new ProcessHandler(proc_ProcessError);
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            txtPrice.TextChanged += new EventHandler(CheckValue);
            t.MethodCompleted += new EventHandler(t_MethodCompleted);
            this.Load += new EventHandler(frmPackageDetails_Load);
            lstServices.SelectedValueChanged += new EventHandler(lstServices_SelectedValueChanged);
            lstServices.SelectedIndexChanged += new EventHandler(lstServices_SelectedIndexChanged);
            txtCategory.SelectedIndexChanged += new EventHandler(txtCategory_SelectedIndexChanged);
            txtCategory.SelectedValueChanged += new EventHandler(txtCategory_SelectedValueChanged);
            mnuRemoveEntry.Click +=new EventHandler(mnuRemoveEntry_Click);
            txtPrice.TextChanged += new EventHandler(CheckValue);
            btnAttach.Click += new EventHandler(btnAttach_Click);
        }

        void btnAttach_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Please double check your entries before committing.\r\n" +
                "Do you wish to continue saving?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlg == System.Windows.Forms.DialogResult.No) return;
            CommitPackageDetails();
        }

        void txtCategory_SelectedValueChanged(object sender, EventArgs e)
        {
            constructAutoComplete();
        }

        void txtCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            constructAutoComplete();
        }

        void lstServices_SelectedIndexChanged(object sender, EventArgs e)
        {
            constructAutoComplete();
        }

        void lstServices_SelectedValueChanged(object sender, EventArgs e)
        {
            constructCategory();

        }

        void frmPackageDetails_Load(object sender, EventArgs e)
        {
            txtPackageName.Text = packageName;
            txtID.Text = packageID;
            lstServices.SelectedIndex = 0;
            txtCategory.SelectedIndex = 0;
            txtDays.SelectedIndex = 0;
            
            InitData();
        }

        void CheckValue(object sender, EventArgs e)
        {
            t.MethodCall(CheckEntry);
        }
        void mnuRemoveEntry_Click(object sender, EventArgs e)
        {
             if (grdItems.SelectedRows.Count == 0) return;
             DialogResult dlg = MessageBox.Show("The entry will be permanently deleted from the list.\r\n" +
                 "Do you wish to continue?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
             if (dlg == System.Windows.Forms.DialogResult.No) return;
             int sel = grdItems.SelectedRows[0].Index;
             DeleteItem();
             t.MethodCall(CheckEntry);
        }
        //UnityCalls
        void t_MethodCompleted(object sender, EventArgs e)
        {
            t.SafeCall(this, delegate
            {
                switch (sender.ToString())
                {
                    case "CheckEntry":
                        lblWarning.Text = wrnEntMsg;
                        if (prcErr)
                        {
                            txtPrice.ForeColor = Color.Red;
                            btnAttach.Enabled = false;
                        }
                        else
                        {
                            txtPrice.ForeColor = Color.Black;
                            if (!pamtErr) btnAttach.Enabled = true;
                        }
                        
                        break;
                }
            });
        }
        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(desc);
            });
        }
        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "DELETE":
                    case "COMMIT":
                    case "LOADDETAILS":
                        proc.DBPUX_Data_Fetch(out dat);
                        grdItems.DataSource = dat[0].ToDataTable();
                        amenities = dat[1].ToDataTable();
                        functionhall = dat[2].ToDataTable();
                        room = dat[3].ToDataTable();
                        food = dat[4].ToDataTable();

                        lstADetails.AddRange(dat[1].ToList<string>(1));
                        lstFDetails.AddRange(dat[2].ToList<string>(0));
                        lstRDetails.AddRange(dat[3].ToList<string>(1));
                        lstFoodDetails.AddRange(dat[4].ToList<string>(0));
                        lstamenities.AddRange(dat[5].ToList<string>(0));
                        txtDetails.Text = "";
                        txtPrice.Text = "";
                        break;
                    
                }
            });
        }

        //Operations
        void CommitPackageDetails()
        {
            PackageItemDetailType [] buf;
            if(lstServices.Text.Equals("FOOD"))
                buf = new PackageItemDetailType[5];
            else
                buf = new PackageItemDetailType[3];

            if (lstServices.Text.Equals("FOOD"))
            {
                buf[0].KeyID = "CATEGORY";
                buf[0].StringData = lstServices.Text;

                buf[3].KeyID = "MEAL_TIME";
                buf[3].StringData = txtCategory.Text;

                buf[4].KeyID = "DAY";
                buf[4].StringData = txtDays.Text;
            }
            else
            {
                buf[0].KeyID = "CATEGORY";
                buf[0].StringData = txtCategory.Text;
            }
            buf[1].KeyID = "TYPE";
            buf[1].StringData = txtDetails.Text;

            buf[2].KeyID = "ORIG_PRICE";
            buf[2].NumericData = float.Parse(txtPrice.Text);

            

            UnityScript u = new UnityScript("COMMIT", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            //Construct Package Items

            u.Script_Add(Script.DBPUX_INSERT, "tblpackageitemdetails(fPackageID, fKeyID, fStringData)",
                    new string[]{
                        txtID.Text,
                        buf[0].KeyID,
                        buf[0].StringData
                    });

            u.Script_Add(Script.DBPUX_INSERT, "tblpackageitemdetails(fPackageID, fKeyID, fStringData)",
                    new string[]{
                        txtID.Text,
                        buf[1].KeyID,
                        buf[1].StringData
                    });

            u.Script_Add(Script.DBPUX_INSERT, "tblpackageitemdetails(fPackageID, fKeyID, fNumericData)",
                    new string[]{
                        txtID.Text,
                        buf[2].KeyID,
                        buf[2].NumericData.ToString()
                    });

            if (lstServices.Text.Equals("FOOD"))
            {
                u.Script_Add(Script.DBPUX_INSERT, "tblpackageitemdetails(fPackageID, fKeyID, fStringData)",
                    new string[]{
                        txtID.Text,
                        buf[3].KeyID,
                        buf[3].StringData
                    });

                u.Script_Add(Script.DBPUX_INSERT, "tblpackageitemdetails(fPackageID, fKeyID, fStringData)",
                        new string[]{
                        txtID.Text,
                        buf[4].KeyID,
                        buf[4].StringData
                    });
            }
                
                u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fKeyID AS 'Service Type', fStringData AS 'Details'," +
                    " fDateTimeData AS 'Date and Time', fNumericData AS 'Price', fStamp FROM tblpackageitemdetails WHERE fPackageID = '"+packageID+"'");
                u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblamenitieslookup");
                u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblfunctionlookup");
                u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblroomlookup");
                u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblfoodlookup");
                u.Script_Add(Script.DBPUX_QUERY, "SELECT fData FROM tbllookup WHERE fKey='AMENITIES'");
            u.Script_Add(Script.DBPUX_COMMIT);
            //Wait if UnityCall is in progress.
            System.Threading.Thread.Sleep(10);
            while (proc.IsRunning)
            {

            }
            proc.Run(u);
        }
        void CheckEntry()
        {
            float fprice = 0f;
            string price = txtPrice.Text;
            //Check Price
            if (!float.TryParse(price, out fprice))
            {
                prcErr = true;
                wrnEntMsg = "";
                wrnEntMsg += "Invalid AMOUNT value detected!\r\n";
            }
            else
            {
                prcErr = false;
                if (!prcErr) wrnEntMsg = "";
            }
        }
        void DeleteItem()
        {
            curDat = grdItems.SelectedRows[0].Index;

            UnityElement ue;
            dat[0].Data_Get(curDat, out ue);
            UnityScript u = new UnityScript("DELETE", 1);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_DELETE, "tblpackageitemdetails",
                string.Format("(fID='{0}') AND (fStamp='{1}')", ue.Data_ID, ue.Data_Stamp));
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fKeyID AS 'Service Type', fStringData AS 'Details'," +
                    " fDateTimeData AS 'Date and Time', fNumericData AS 'Price', fStamp FROM tblpackageitemdetails WHERE fPackageID = '" + packageID + "'");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblamenitieslookup");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblfunctionlookup");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblroomlookup");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblfoodlookup");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fData FROM tbllookup WHERE fKey='AMENITIES'");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
            
        }
        private void InitData()
        {
            UnityScript u = new UnityScript("LOADDETAILS", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fKeyID AS 'Service Type', fStringData AS 'Details'," +
                    " fDateTimeData AS 'Date and Time', fNumericData AS 'Price', fStamp FROM tblpackageitemdetails WHERE fPackageID = '" + packageID + "'");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblamenitieslookup");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblfunctionlookup");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblroomlookup");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT * FROM tblfoodlookup");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fData FROM tbllookup WHERE fKey='AMENITIES'");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        private void constructCategory()
        {
            txtCategory.Items.Clear();

            switch (lstServices.Text)
            {
                case "FOOD":
                    txtDays.Enabled = true;
                    txtCategory.Items.AddRange(lstmealtime);
                    break;
                case "AMENITIES":
                    txtDays.Enabled = false;
                    txtCategory.Items.AddRange(lstamenities.ToArray());
                    break;
                case "RESERVATION":
                    txtDays.Enabled = false;
                    txtCategory.Items.AddRange(lstreservation);
                    break;
            }

            txtCategory.SelectedIndex = 0;
            constructAutoComplete();
        }
        private void constructAutoComplete()
        {
            txtDetails.AutoCompleteCustomSource.Clear();
            switch (lstServices.Text)
            {
                case "FOOD":
                    txtDetails.AutoCompleteCustomSource.AddRange(lstFoodDetails.ToArray());
                    break;
                case "AMENITIES":
                    txtDetails.AutoCompleteCustomSource.AddRange(lstADetails.ToArray());
                    break;
                case "RESERVATION":
                    if (txtCategory.Text.Equals("ROOM"))
                    {
                        txtDetails.AutoCompleteCustomSource.AddRange(lstRDetails.ToArray());
                    }
                    else
                    {
                        txtDetails.AutoCompleteCustomSource.AddRange(lstFDetails.ToArray());
                    }
                    break;
            }

        }
        void States(bool s)
        {
            grpType.Enabled = s;
            btnAttach.Enabled = s;
        }
    }
}
